package com.ego.member.oauth2;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.ego.common.constant.MemberConstant;
import com.ego.common.to.member.MemberTo;
import com.ego.member.po.Member;
import com.ego.member.service.MemberService;
import com.ego.member.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.ApplicationContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: ego
 * @description: 支付宝登录
 * @author: KamTang
 * @create: 2022-12-15 14:25
 **/
@Slf4j
public class ZfbOauth2 implements Oauth2 {

    private final ApplicationContext applicationContext = SpringUtil.getApplicationContext();

    private final MemberService memberService = applicationContext.getBean(MemberService.class);

    @Override
    public MemberTo oauth2Login(HttpServletRequest request) {
        // 上线url
        String url = "https://openapi.alipay.com/gateway.do";
        // 我的appid
        String appId = "2021003169634351";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkReLx3zTix4JCcpNDSXdM6rlv1JwaaKauthkQPvVhzhLpm08qrQ10GiB91gnvLYYX9No7MEWI3B247nYYoYewvrQHbnGg3A3+QAcE3TDfUQMQnyZOShXhkFnUbHjwf4kh7kS/1WV302T+laqo0e2Dl2k1oHsSXuZ/5p3/aYiJ/voBnQdJh3DX6qkRP44xgf32Y4Uctu6eoS/XYlKpmZheB1CIggOBMAolH2uz0fExq6hHVwHBGJJwuHqWZi/FYH/JMkwut0JRY/YRvWyn7RChktqJrOMsjIoT4hYLX774lPrKh1EdgSDbqjIhfIA/WuS9Toi8shTNYFKnqRpPkdV6QIDAQAB";
        String authCode = request.getParameter("auth_code");
        AlipayClient alipayClient = new DefaultAlipayClient(url,
                appId,
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCGTQPvC9Z3issriyXmNhz8w2Yk2F8N65wp0+Q6vNctoLWNvQAjJdZ83QEx3JG9rtrcecx6YUUCBHxvY5HrdtsRqqipzeQhphtiVG+gIlJokeMGdkX9fnisnkF/mXFoiDgkkFRrMNt6LY4zj8UAlXMejbjIMV0BDFXfAp38LC2IYwWFA03HCa9jvtCYMjdfxGJ1VfSxs6ztI2yMNKhERm8pdhTP1Ri+2GE6/pwJBKdwpuEue7WzOMYbzrI/OjJQeig192+XuU3enZrX+MRNauL++yBsgEdN/X8SaP0+EcLmZ2XE9j6qTOxFaqoZPQfENj9wcs0mGc8h30fhoqnzl4P5AgMBAAECggEAEOupIDgMmFkbSewpJT0SH+J6fw/nwfg6X6a7rY7XSX9jAG2ck9ETmf26Rc71acGa/4Y09gJFUIDCMMKJwvHhnfMzdtli8b5c2uGqgrFwUo523PyPyuVhTNZPiEUL3dCzyh+JE0w/isAsl2B4wJ8TtvjCHC7j+drVAtjwkLH8Np+baQ578dlPrDHrlEB0vQO5sQ0J2ZE81HPnNFIfs4VawT2kKkMNa6VXC4OxkgjU+lSDU9HoIfpDyVRfbFSX2342D7JPeo59PImSossdcoTI29sOAaHGcz03GwZWxNvb7vVi07hwjq+fGjnDbUKU84K70gF+X3trppfmaVh64fYR9QKBgQDlsfIklzpGmPKombEDm2CVM+pG/un65RLeiiy7T2bnDEOYdDW9vskok+VKfwIHBjM3h5iE8vtKI/96O9pHo9NR6EspcuQ+jNEQiWYFGbiLlVA16jQifwhtCwhTsVMjRkRYnOLNempVqmQzfy3cUokpbnigLuFxp+nXpcNkp17UJwKBgQCVrlyQBEXMJPBQWyS/pIDclBXsrgKzEHGrfFzQWdIJUfwXmRDPFqs2RRp2iQlilr3F2u+X75Ip2drKfDpNkxI/sFjeKRyfnH5XwlGhit9o2SEzWNoT2UrBOZccmXfBPVE5Ff4Kb5fAT4jges6U8qGqjlKWWVqutNlpIFgOIMFa3wKBgC+K9oDGYISOUeO99Bq4BXS8iyhoyQtqcM5pMTsQA0+dhTxACYOdwstIWXRi94t2qBE9Wr9h/8tnyhCF5PdhHHNerngE1ONxiDBxEBHMMhuKK1ENif795kOTvgR8tqWdfLYOuw8m4G2c2CKkl1x8JPHTcNpO+dDpnYhKQjhKQGGPAoGAJffEowNycQYtrzRvbe1cgpdNuGurY6CYNNem83LVRGf3ekTpbp5hb7K3s7mvF8MFAFs4y2GJwfPw+8vnPiZASseAw1nKWPJpWfmAm2mOohnxwgSXzNEhlUH2gtqq9emH4OMjPaJw6+dA4TBFlqK1P346lMi1p/tX6sK5k1vbsCECgYBPfs3VA1CYjeYdjxE4VTC5Uk3MvLY9D1YrxNKdi6FyVqqVKQrODdKQwcxMXWmhlR4oxcRx8EarDvc0//G29Fg/3Zm4G9l+SdUa2FYB6x+85vCmnyx+b1D2nX+OWaNl5vgyUb8nhqQbagBb28S6rPDZreB1wROolzbVi17EyKCCkg==",
                "json",
                "utf-8",
                alipayPublicKey,
                "RSA2");
        AlipaySystemOauthTokenRequest oauthTokenRequest = new AlipaySystemOauthTokenRequest();
        oauthTokenRequest.setCode(authCode);
        oauthTokenRequest.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(oauthTokenRequest);
            String accessToken = oauthTokenResponse.getAccessToken();
            AlipayUserInfoShareRequest infoShareRequest = new AlipayUserInfoShareRequest();
            AlipayUserInfoShareResponse userinfoShareResponse = alipayClient.execute(infoShareRequest, accessToken);
            MemberTo memberTo = buildMember(oauthTokenResponse, userinfoShareResponse);
            Member member = memberService.oauth2Login(memberTo);
            if (ObjectUtils.isNotEmpty(member)) {
                return member.toTo();
            }
        } catch (AlipayApiException e) {
            // 处理异常
            log.error("通过支付宝获取用户信息失败，原因：{}", e.getMessage());
        }
        return null;
    }

    private MemberTo buildMember(AlipaySystemOauthTokenResponse oauthTokenResponse,
                                 AlipayUserInfoShareResponse userinfoShareResponse) {
        MemberTo to = new MemberTo();
        to.setSocialUid(oauthTokenResponse.getUserId());
        to.setAccessToken(oauthTokenResponse.getAccessToken());
        to.setExpireTime(Long.parseLong(oauthTokenResponse.getExpiresIn()));
        to.setUsername(userinfoShareResponse.getNickName());
        to.setNickname(userinfoShareResponse.getNickName());
        to.setLevelId(MemberConstant.DEFAULT_MEMBER_LEVEL);
        to.setHeader(userinfoShareResponse.getAvatar());
        to.setCreateTime(new Date());
        return to;
    }

    /**
     * 验签
     */
    private boolean signVerified(HttpServletRequest request, String alipayPublicKey) throws AlipayApiException {
        // 获取支付宝POST过来反馈信息
        Map< String , String > params = new HashMap<>(4);
        Map<String,String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return AlipaySignature.rsaCheckV1(params, alipayPublicKey, "utf-8","RSA2");
    }

}
